package com.feicheng.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.task.Cache;
import com.feicheng.persistence.entity.Asetting;
import com.feicheng.persistence.entity.CnRegionInfo;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class LocationUtils {

    @Autowired
    Cache cache;

    @Autowired
    RestTemplate restTemplate;

    public JSONObject getJWD(String address) {

        Asetting asetting = cache.getObject("Asetting", Asetting.class);

        try {
            StringBuilder sbUrl = new StringBuilder();
            sbUrl.append("https://apis.map.qq.com/ws/geocoder/v1")
                    .append(Constant.HTTP.REQUEST.QU)
                    .append("key").append(Constant.HTTP.REQUEST.EQ).append(asetting.getLocationkey())
                    .append(Constant.HTTP.REQUEST.AD).append("address").append(Constant.HTTP.REQUEST.EQ).append(address);
            ResponseEntity<String> result = restTemplate.getForEntity(sbUrl.toString(), String.class);

            JSONObject jo = JSON.parseObject(result.getBody());
            if (jo.containsKey("message")) {
                if ("Success".equals(jo.getString("message"))) {
                    JSONObject location = jo.getJSONObject("result");
                    return location;
                }
            }
        } catch(Exception e) {
            log.error("取得经纬度失败：", e);
        }

        throw new SystemException("解析经纬度失败");
    }

    public String getCnCode(String cnname) {
        JSONObject cns = cache.getJSONObject("cns");
        if (cns.containsKey(cnname)) {
            CnRegionInfo cn = cns.getObject(cnname, CnRegionInfo.class);
            return cn.getCricode();
        }
        throw new SystemException("没找到对应的区域");
    }




}
